import book.Book;
import book.BookList;
import user.AdminUser;
import user.NormalUser;
import user.User;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

class Main {
    private JFrame frame;
    private BookList bookList;
    private User currentUser;
    private String regName;
    private String regPassword;
    private int regType; // 1: 管理员, 2: 普通用户

    public Main() {
        bookList = new BookList(readBooksFromFile("books.txt"));
        showRegisterFrame();
    }

    // 注册界面
    private void showRegisterFrame() {
        frame = new JFrame("图书管理系统 - 注册");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(350, 250);
        frame.setLocationRelativeTo(null);
        frame.setLayout(new GridLayout(5, 2, 5, 5));

        JLabel userTypeLabel = new JLabel("请选择身份:");
        JComboBox<String> userTypeBox = new JComboBox<>(new String[]{"管理员", "普通用户"});
        JLabel nameLabel = new JLabel("用户名:");
        JTextField nameField = new JTextField();
        JLabel passLabel = new JLabel("密码:");
        JPasswordField passField = new JPasswordField();
        JButton registerBtn = new JButton("注册");

        frame.add(userTypeLabel);
        frame.add(userTypeBox);
        frame.add(nameLabel);
        frame.add(nameField);
        frame.add(passLabel);
        frame.add(passField);
        frame.add(new JLabel());
        frame.add(registerBtn);

        registerBtn.addActionListener(e -> {
            regType = userTypeBox.getSelectedIndex() == 0 ? 1 : 2;
            regName = nameField.getText().trim();
            regPassword = new String(passField.getPassword());
            if (regName.isEmpty() || regPassword.isEmpty()) {
                JOptionPane.showMessageDialog(frame, "用户名和密码不能为空！");
                return;
            }
            JOptionPane.showMessageDialog(frame, "注册成功！请登录。");
            frame.dispose();
            showLoginFrame();
        });

        frame.setVisible(true);
    }

    // 登录界面
    private void showLoginFrame() {
        frame = new JFrame("图书管理系统 - 登录");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(350, 250);
        frame.setLocationRelativeTo(null);
        frame.setLayout(new GridLayout(5, 2, 5, 5));

        JLabel userTypeLabel = new JLabel("请选择身份:");
        JComboBox<String> userTypeBox = new JComboBox<>(new String[]{"管理员", "普通用户"});
        JLabel nameLabel = new JLabel("用户名:");
        JTextField nameField = new JTextField();
        JLabel passLabel = new JLabel("密码:");
        JPasswordField passField = new JPasswordField();
        JButton loginBtn = new JButton("登录");

        frame.add(userTypeLabel);
        frame.add(userTypeBox);
        frame.add(nameLabel);
        frame.add(nameField);
        frame.add(passLabel);
        frame.add(passField);
        frame.add(new JLabel());
        frame.add(loginBtn);

        loginBtn.addActionListener(e -> {
            int type = userTypeBox.getSelectedIndex() == 0 ? 1 : 2;
            String name = nameField.getText().trim();
            String password = new String(passField.getPassword());
            if (!Objects.equals(name, regName) || !Objects.equals(password, regPassword) || type != regType) {
                JOptionPane.showMessageDialog(frame, "用户名、密码或身份错误！");
                return;
            }
            if (type == 1) {
                currentUser = new AdminUser(name, password);
            } else {
                currentUser = new NormalUser(name, password);
            }
            JOptionPane.showMessageDialog(frame, "登录成功！");
            frame.dispose();
            showMenuFrame();
        });

        frame.setVisible(true);
    }

    // 主菜单界面
    private void showMenuFrame() {
        frame = new JFrame("图书管理系统 - 主菜单");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 350);
        frame.setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(0, 1, 10, 10));

        // 管理员和普通用户菜单不同
        if (regType == 1) { // 管理员
            addMenuButton(panel, "添加图书", this::showAddBookDialog);
            addMenuButton(panel, "删除图书", this::showDelBookDialog);
            addMenuButton(panel, "查找图书", this::showFindBookDialog);
            addMenuButton(panel, "显示所有图书", this::showAllBooksDialog);
        } else { // 普通用户
            addMenuButton(panel, "查找图书", this::showFindBookDialog);
            addMenuButton(panel, "借阅图书", this::showBorrowBookDialog);
            addMenuButton(panel, "归还图书", this::showReturnBookDialog);
            addMenuButton(panel, "显示所有图书", this::showAllBooksDialog);
        }
        addMenuButton(panel, "退出", () -> {
            writeBooksToFile(bookList, "books_output.txt");
            JOptionPane.showMessageDialog(frame, "已保存并退出");
            System.exit(0);
        });

        frame.setContentPane(panel);
        frame.setVisible(true);
    }

    private void addMenuButton(JPanel panel, String text, Runnable action) {
        JButton btn = new JButton(text);
        btn.addActionListener(e -> action.run());
        panel.add(btn);
    }

    // 下面是各功能的对话框实现
    private void showAddBookDialog() {
        JTextField nameField = new JTextField();
        JTextField authorField = new JTextField();
        JTextField typeField = new JTextField();
        JTextField priceField = new JTextField();
        Object[] message = {
                "书名:", nameField,
                "作者:", authorField,
                "类型:", typeField,
                "价格:", priceField
        };
        int option = JOptionPane.showConfirmDialog(frame, message, "添加图书", JOptionPane.OK_CANCEL_OPTION);
        if (option == JOptionPane.OK_OPTION) {
            try {
                String name = nameField.getText().trim();
                String author = authorField.getText().trim();
                String type = typeField.getText().trim();
                int price = Integer.parseInt(priceField.getText().trim());
                for (Book b : bookList.getBooks()) {
                    if (b.getName().equals(name)) {
                        JOptionPane.showMessageDialog(frame, "该书已存在！");
                        return;
                    }
                }
                bookList.setBook(new Book(name, author, price, type, false));
                JOptionPane.showMessageDialog(frame, "添加成功！");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(frame, "输入有误！");
            }
        }
    }

    private void showDelBookDialog() {
        String name = JOptionPane.showInputDialog(frame, "请输入要删除的书名:");
        if (name == null) return;
        int index = -1;
        for (int i = 0; i < bookList.getUsedsize(); i++) {
            if (bookList.getBook(i).getName().equals(name)) {
                index = i;
                break;
            }
        }
        if (index == -1) {
            JOptionPane.showMessageDialog(frame, "没有该书！");
            return;
        }
        int confirm = JOptionPane.showConfirmDialog(frame, bookList.getBook(index).toString() + "\n确认删除？", "确认", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            bookList.getBooks().remove(index);
            JOptionPane.showMessageDialog(frame, "删除成功！");
        }
    }

    private void showFindBookDialog() {
        String name = JOptionPane.showInputDialog(frame, "请输入要查找的书名:");
        if (name == null) return;
        for (Book b : bookList.getBooks()) {
            if (b.getName().equals(name)) {
                JOptionPane.showMessageDialog(frame, "查找成功！\n" + b.toString());
                return;
            }
        }
        JOptionPane.showMessageDialog(frame, "没有该书！");
    }

    private void showBorrowBookDialog() {
        String name = JOptionPane.showInputDialog(frame, "请输入要借阅的书名:");
        if (name == null) return;
        for (Book b : bookList.getBooks()) {
            if (b.getName().equals(name)) {
                if (!b.isIsborrow()) {
                    b.setIsborrow(true);
                    JOptionPane.showMessageDialog(frame, "借阅成功！");
                } else {
                    JOptionPane.showMessageDialog(frame, "该书已被借出！");
                }
                return;
            }
        }
        JOptionPane.showMessageDialog(frame, "没有该书！");
    }

    private void showReturnBookDialog() {
        String name = JOptionPane.showInputDialog(frame, "请输入要归还的书名:");
        if (name == null) return;
        for (Book b : bookList.getBooks()) {
            if (b.getName().equals(name)) {
                if (b.isIsborrow()) {
                    b.setIsborrow(false);
                    JOptionPane.showMessageDialog(frame, "归还成功！");
                } else {
                    JOptionPane.showMessageDialog(frame, "该书未被借出！");
                }
                return;
            }
        }
        JOptionPane.showMessageDialog(frame, "没有该书！");
    }

    private void showAllBooksDialog() {
        StringBuilder sb = new StringBuilder();
        for (Book b : bookList.getBooks()) {
            sb.append(b.toString()).append("\n");
        }
        JOptionPane.showMessageDialog(frame, sb.length() == 0 ? "无图书！" : sb.toString());
    }

    // 从文件读取书籍信息的方法
    public static Book[] readBooksFromFile(String filename) {
        List<Book> bookList = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                //默认书籍为未借阅
                if (parts.length >= 4) {
                    String name = parts[0].trim();
                    String author = parts[1].trim();
                    int price = Integer.parseInt(parts[2].trim());
                    String type = parts[3].trim();

                    // 检查是否有借阅状态信息
                    boolean isborrow = false;
                    if (parts.length >= 5) {
                        String borrowStatus = parts[4].trim();
                        isborrow = borrowStatus.equals("已借出") || borrowStatus.equals("true");
                    }

                    Book book = new Book(name, author, price, type, isborrow);
                    bookList.add(book);
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件 " + filename + " 不存在，将使用默认书籍信息");
            // 如果文件不存在，创建默认的书籍信息
            bookList.add(new Book("三国演义", "罗贯中", 10, "小说", false));
            bookList.add(new Book("西游记", "吴承恩", 20, "小说", false));
            bookList.add(new Book("红楼梦", "曹雪芹", 18, "小说", false));
        } catch (IOException e) {
            System.out.println("读取文件时发生错误: " + e.getMessage());
        }

        return bookList.toArray(new Book[0]);
    }

    // 将书籍信息写入文件的方法
    public static void writeBooksToFile(BookList bookList, String filename) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(filename))) {
            for (int i = 0; i < bookList.getUsedsize(); i++) {
                Book book = bookList.getBook(i);
                if (book != null) {
                    writer.println(book.getName() + "," + book.getAuthor() + "," +
                            book.getPrice() + "," + book.getType() + "," +
                            (book.isIsborrow() ? "已借出" : "未借出"));
                }
            }
        } catch (IOException e) {
            System.out.println("写入文件时发生错误: " + e.getMessage());
        }
    }
    public static void main(String[] args) {
        Main main = new Main();
    }
}